import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userApi } from '@/utils/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>('')
  const userInfo = ref<any>(null)
  const userId = ref<number>(0)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const displayName = computed(() => {
    if (!userInfo.value) return '未登录'
    return userInfo.value.nickname || userInfo.value.username || '用户'
  })

  // 初始化
  const init = () => {
    const storedToken = uni.getStorageSync('token')
    const storedUserInfo = uni.getStorageSync('userInfo')
    const storedUserId = uni.getStorageSync('userId')
    
    if (storedToken) {
      token.value = storedToken
    }
    if (storedUserInfo) {
      userInfo.value = storedUserInfo
    }
    if (storedUserId) {
      userId.value = storedUserId
    }
  }

  // 登录
  const login = async (code: string) => {
    try {
      const result = await userApi.wechatLogin(code)
      
      // 保存数据
      token.value = result.token
      userInfo.value = result.user_info
      userId.value = result.user_id
      
      // 保存到本地存储
      uni.setStorageSync('token', result.token)
      uni.setStorageSync('userInfo', result.user_info)
      uni.setStorageSync('userId', result.user_id)
      
      return result
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const result = await userApi.getUserInfo()
      userInfo.value = result
      uni.setStorageSync('userInfo', result)
      return result
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 获取用户资料
  const fetchUserProfile = async () => {
    try {
      const result = await userApi.getUserProfile(userId.value)
      return result
    } catch (error) {
      console.error('获取用户资料失败:', error)
      throw error
    }
  }

  // 更新用户资料
  const updateProfile = async (data: any) => {
    try {
      const result = await userApi.updateUserProfile(userId.value, data)
      return result
    } catch (error) {
      console.error('更新用户资料失败:', error)
      throw error
    }
  }

  // 上传头像
  const uploadAvatar = async (filePath: string) => {
    try {
      const result = await userApi.uploadAvatar(userId.value, filePath)
      return result
    } catch (error) {
      console.error('上传头像失败:', error)
      throw error
    }
  }

  // 检查登录状态
  const checkLoginStatus = () => {
    const storedToken = uni.getStorageSync('token')
    if (storedToken) {
      token.value = storedToken
      const storedUserInfo = uni.getStorageSync('userInfo')
      if (storedUserInfo) {
        userInfo.value = storedUserInfo
      }
      const storedUserId = uni.getStorageSync('userId')
      if (storedUserId) {
        userId.value = storedUserId
      }
      return true
    }
    return false
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    userId.value = 0
    
    // 清除本地存储
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('userId')
  }

  return {
    // 状态
    token,
    userInfo,
    userId,
    
    // 计算属性
    isLoggedIn,
    displayName,
    
    // 方法
    init,
    login,
    fetchUserInfo,
    fetchUserProfile,
    updateProfile,
    uploadAvatar,
    checkLoginStatus,
    logout
  }
}) 